<template>
  <div>
    <el-card>
      <el-table
        :data="cate1list"
        style="width: 100%"
        border
        :load="load"
        :row-key="getRowKey"
        lazy
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="分类id" width="150" align="center"> </el-table-column>
        <el-table-column prop="name" label="分类名称"> </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" class="button" @click="developing"
              ><i class="el-icon-plus icon"></i
            ></el-button>
            <el-button type="primary" size="mini" class="button" @click="developing"
              ><i class="el-icon-edit-outline icon"></i
            ></el-button>

            <el-button type="danger" size="mini" class="button" @click="developing"
              ><i class="el-icon-delete icon"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from 'vuex'
import { nanoid } from 'nanoid'
export default {
  name: 'Category',
  data() {
    return {
      cate1list: []
    }
  },
  methods: {
    ...mapActions('attr', ['getCategory1List', 'getCategory2List', 'getCategory3List']),
    ...mapMutations('attr', ['SETCATEGORY1ID', 'SETCATEGORY2ID', 'SETCATEGORY3ID']),
    developing() {
      this.$message('功能正在实现中...')
    },
    async load(row, treeNode, resolve) {
      if (row.level == 1) {
        const { id } = row
        this.SETCATEGORY1ID(id)
        await this.getCategory2List()
        const result2 = this.category2List.map((item, index) => {
          return { ...item, hasChildren: true, level: 2, parentId: id }
        })
        resolve(result2)
      }
      if (row.level == 2) {
        const { id } = row
        this.SETCATEGORY2ID(id)
        await this.SETCATEGORY3ID()
        const result3 = this.category2List.map((item, index) => {
          return { ...item, level: 3, parentId: id }
        })
        resolve(result3)
      }
    },
    //绑定的row-key默认可以拿到row
    getRowKey(row) {
      return row.level + '-' + row.id + '-' + row.parentId
    }
  },
  computed: {
    ...mapState('attr', ['category1List', 'category2List', 'category3List'])
  },
  async mounted() {
    await this.getCategory1List()
    this.cate1list = this.category1List.map((item, index) => {
      return { ...item, hasChildren: true, level: 1, index }
    })
  }
}
</script>

<style lang="less" scoped></style>
